<template>
    <div class="login">
        <van-form @submit="onSubmit">
            <van-field
                v-model="username"
                name="username"
                placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
            />
            <van-field
                v-model="password"
                type="password"
                name="password"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
            <div style="margin: 16px">
                <van-button round block type="info" native-type="submit"
                    >登录</van-button
                >
            </div>
        </van-form>
    </div>
</template>

<script>
export default {
    beforeRouteEnter(to, from, next) {
        if (window.sessionStorage.getItem('token')) {
            next('/layout/home')
        } else {
            next()
        }
        // 在渲染该组件的对应路由被 confirm 前调用
        // 不！能！获取组件实例 `this`
        // 因为当守卫执行前，组件实例还没被创建
    },
    data() {
        return {
            username: '',
            password: '',
        }
    },
    methods: {
        onSubmit(values) {
            this.$api.login(values).then((res) => {
                if (res.code === 1) {
                    window.sessionStorage.setItem(
                        'user',
                        JSON.stringify(res.data)
                    )
                    window.sessionStorage.setItem('token', res.data.token)
                    this.$router.push('/layout/home')
                }
            })
        },
    },
}
</script>

<style lang='scss'>
@import '@css/style.scss';
.login {
    padding: px2rem(30);
}
/deep/.van-button--info {
    background-color: $btnColor;
}
</style>